package org.example.expansionpoint.beanPostProcessor;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Description:
 */

@SpringBootApplication
@Slf4j
public class TestBeanPostProcessor {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TestBeanPostProcessor.class, args);
        context.close();
    }


    @Data
    static class Fish implements InitializingBean {
        private Double weight;
        private Double price;

        public Fish() {
            log.info("1：执行了无参构造");
        }

        @Override
        public void afterPropertiesSet() throws Exception {
            log.info("3：执行了 afterPropertiesSet() 方法");
        }

        public void init() {
            log.info("4：执行了 init() 方法");
        }
    }

    @Configuration
    static class TestConfiguration1 {

        @Bean(name = "fish", initMethod = "init")
        public Fish fish() {
            return new Fish();
        }
    }

    @Component
    static class MyBeanPostProcessor implements BeanPostProcessor {

        // 每个Bean 实例化后、初始化之前 都会执行
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if ("fish".equals(beanName)) {
                log.info("2：执行了 postProcessBeforeInitialization() 方法");
            }
            return bean;
        }


        // 每个Bean 初始化后、自定义初始化方法后 都会执行
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if ("fish".equals(beanName)) {
                log.info("5：执行了 postProcessAfterInitialization() 方法");
            }
            return bean;
        }
    }

}
